package com.fecean.aabbc.netty.handler7;

import com.fecean.aabbc.netty.dispatcher7.ChannelSender;
import com.fecean.aabbc.netty.message7.MessageBuilder;
import com.fecean.aabbc.netty.message7.MessageType;
import com.fecean.aabbc.netty.message7.ResponseMessage;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 ** 响应通道处理
 *
 * @author: chenfenghai
 * @version: 1.0
 * @date: 2020-03-05 15:59
 * @blame Team
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class NettyResponseChannelHandler extends ChannelInboundHandlerAdapter {

    /**
     ** 请求发送对象
     */
    @Resource
    ChannelSender requestSender;

    /**
     ** 根据请求唯一KEY，移除ResponseFuture
     *
     * @param requestUniqueKey 请求唯一KEY
     */
    public void removeResponseFuture(String requestUniqueKey){
        requestSender.remove(requestUniqueKey);
    }

    /**
     ** 读取数据处理，把响应结果设置到对应的ResponseFuture中
     *
     * @param ctx 通道上下文
     * @param msg 读取到的数据
     * @throws Exception 处理过程中存在异常则抛出
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        MessageBuilder messageBuilder = MessageBuilder.of(msg);
        if(messageBuilder.isMessage(MessageType.RESPONSE)){
            log.info("客户端[{}-{}]收到响应：{}", messageBuilder.getMessage().getTenantId(),
                    messageBuilder.getMessage().getCinemaCode(), messageBuilder.getMessage());

            // 处理响应消息
            requestSender.received((ResponseMessage) messageBuilder.getMessage());
            return;
        }
        ctx.fireChannelRead(msg);
    }
}
